package com.controller;

import com.model.UserModel;
import com.services.IUserServices;
import com.services.impl.UserServicesImpl;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Program: exam
 * @ClassName: RegisterServletController
 * @Description: 添加用户
 * @Author: li
 * @Create: 2019-07-23 10:18
 */
@WebServlet("/RegisterServlet")
public class RegisterServletController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应格式
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        try {
            // 读取JSON数据
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            // 解析JSON数据
            JSONObject jsonObject = JSONObject.fromObject(sb.toString());
            
            // 创建用户对象
            UserModel userModel = new UserModel(
                jsonObject.getString("email"),
                jsonObject.getString("username"),
                jsonObject.getString("password"), // 前端传password而不是pwd
                jsonObject.getString("sex"),
                jsonObject.getString("tel"),
                jsonObject.getString("address"),
                1  // 默认状态为1
            );
            
            // 打印日志
            System.out.println("接收到的用户数据: " + userModel);
            
            // 调用service注册用户
            IUserServices services = new UserServicesImpl();
            services.register(userModel);
            
            // 返回成功响应
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("msg", "添加用户成功");
            
            response.getWriter().write(JSONObject.fromObject(result).toString());
            
        } catch (Exception e) {
            // 返回错误响应
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("msg", "添加用户失败: " + e.getMessage());
            
            response.getWriter().write(JSONObject.fromObject(result).toString());
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
